package com.pangu.core.engine.game.task.zhajinhua;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.cache2k.expiry.ValueWithExpiryTime;

import com.alibaba.fastjson.JSONObject;
import com.pangu.core.BMDataContext;
import com.pangu.core.BMDataContext.PlayerTypeEnum;
import com.pangu.core.cache.CacheHelper;
import com.pangu.core.engine.game.ActionTaskUtils;
import com.pangu.core.engine.game.BeiMiGameEvent;
import com.pangu.core.engine.game.BeiMiGameTask;
import com.pangu.core.engine.game.task.AbstractTask;
import com.pangu.util.GameUtils;
import com.pangu.util.rules.model.BetStatus;
import com.pangu.util.rules.model.Board;
import com.pangu.util.rules.model.NextPlayer;
import com.pangu.util.rules.model.ZhajinhuaBoard;
import com.pangu.util.rules.model.ZhajinhuaTakeCards;
import com.pangu.web.model.GameRoom;
import com.pangu.web.model.PlayUserClient;

import lombok.extern.slf4j.Slf4j;

/**
 * 出牌计时器，默认25秒，超时执行
 * 
 * @author zhangtianyi
 *
 */
@Slf4j
public class CreateZhajinhuaPlayCardsTask extends AbstractTask implements ValueWithExpiryTime, BeiMiGameTask {

	private long timer;
	private GameRoom gameRoom = null;
	private String orgi;
	private String player;

	public CreateZhajinhuaPlayCardsTask(long timer, String userid, GameRoom gameRoom, String orgi) {
		super();
		this.timer = timer;
		this.gameRoom = gameRoom;
		this.orgi = orgi;
		this.player = userid;
	}

	@Override
	public long getCacheExpiryTime() {
		return System.currentTimeMillis() + timer * 1000; // 5秒后执行
	}

	public void execute() {
		// 当前牌局信息
		ZhajinhuaBoard board = (ZhajinhuaBoard) CacheHelper.getBoardCacheBean().getCacheObject(gameRoom.getId(),
				gameRoom.getOrgi());
		// 获取当前操作人指令
		ZhajinhuaTakeCards zhajinhuaTakeCards = board.getZhajinhuaTakeCards();
		// 如果当前操作已存在，说明牌局已经开始
		if (zhajinhuaTakeCards != null) {
			// 当前操作人
			PlayUserClient playUserClient = (PlayUserClient) CacheHelper.getGamePlayerCacheBean()
					.getPlayer(zhajinhuaTakeCards.getUserid(), orgi);
			if (playUserClient != null) {
				// ai
				if (playUserClient.getPlayertype().equals(BMDataContext.PlayerTypeEnum.AI.toString())) {
					// 后端并且开始执行操作
					Map<String, String> map = new HashMap<String, String>();
					// 操作类型：1、加注2、跟注3、弃牌4、比牌
					if (zhajinhuaTakeCards.getActionType() == 1 || zhajinhuaTakeCards.getActionType() == 2) {
						map.put("gametype", BMDataContext.GameTypeEnum.JINHUA.toString());
						map.put("betcoin", zhajinhuaTakeCards.getBetCoin() + "");
						ActionTaskUtils.sendEvent("zhajinhuatakecards", zhajinhuaTakeCards, gameRoom);
						// 调用下注方法
						BMDataContext.getZhajinhuaEngine().execBet(playUserClient, gameRoom, new BetStatus(), map);
						System.out.println("-------------------------------" + playUserClient.getId() + "下注打断记时");
						// 激活注册机到下一步
						BMDataContext.getZhajinhuaEngine().takeCardsRequest(gameRoom.getId(),
								board.getNextplayer().getNextplayer(), playUserClient.getOrgi(), true, null);
					} else if (zhajinhuaTakeCards.getActionType() == 3) {
						ActionTaskUtils.sendEvent("zhajinhuatakecards", zhajinhuaTakeCards, gameRoom);
						BMDataContext.getZhajinhuaEngine().execGiveup(playUserClient, zhajinhuaTakeCards.getRoomId(),
								zhajinhuaTakeCards);
					} else if (zhajinhuaTakeCards.getActionType() == 4) {
						map.put("anotherPlayer", zhajinhuaTakeCards.getCompareUserid());
						JSONObject json = new JSONObject();
						json.put("command", "comparecard");
						json = BMDataContext.getZhajinhuaEngine().execCompareCard(playUserClient, board, json, map);
						Map<String, Object> cardInfoMap = (Map<String, Object>) json.get("cards");
						String winnerUserId = "";
						// 根据输赢，传入赢家userid
						if (cardInfoMap.get("flag").toString().equals("1")) {
							winnerUserId = zhajinhuaTakeCards.getUserid();
						} else if (cardInfoMap.get("flag").toString().equals("2")) {
							winnerUserId = zhajinhuaTakeCards.getCompareUserid();
						}
						// 设置比牌赢了的玩家id
						zhajinhuaTakeCards.setCompareWinUserid(winnerUserId);
						log.info("--" + zhajinhuaTakeCards.getUserid() + "发起和" + zhajinhuaTakeCards.getCompareUserid()
								+ "比牌，赢家是" + winnerUserId);
						ActionTaskUtils.sendEvent("zhajinhuatakecards", zhajinhuaTakeCards, gameRoom);
						int currentPlayerNum = Integer.parseInt(json.get("currentPlayerNum").toString());
						// 存活并且未弃牌人数大于1游戏继续，未弃牌人数小于2前台发起结算
						if (currentPlayerNum > 1) {
							log.info("-----------------------" + zhajinhuaTakeCards.getUserid() + "比牌打断记时");
							// 激活注册机到下一步
							BMDataContext.getZhajinhuaEngine().takeCardsRequest(zhajinhuaTakeCards.getRoomId(),
									board.getNextplayer().getNextplayer(), gameRoom.getOrgi(), true, null);
						} else {
							log.info("--------------------------------------比牌后人数不够进入结算");
							// 进入下一步结算 激活注册机到下一步
							GameUtils.getGame(gameRoom.getPlayway(), gameRoom.getOrgi()).change(gameRoom,
									BeiMiGameEvent.ALLCARDS.toString()); // 通知状态机
						}
					}
				} else {
					// ZhajinhuaTakeCards zhajinhuaTakeCards = new ZhajinhuaTakeCards();
					// zhajinhuaTakeCards.setUserid(playUser.getId());
					zhajinhuaTakeCards.setActionType(3);
					BMDataContext.getZhajinhuaEngine().execGiveup(playUserClient, gameRoom.getId(), zhajinhuaTakeCards);
					ActionTaskUtils.sendEvent("zhajinhuatakecards", zhajinhuaTakeCards, gameRoom);
					log.info("----------------到时弃牌" + zhajinhuaTakeCards.getUserid());
				}
			}
		} else {
			String nextPlayer = board.getBanker();
			NextPlayer nextp = board.getNextplayer();
			String playerId = nextp.getNextplayer();
			// 若下一个出牌的人不为空则覆盖庄家，否则庄家先出牌
			if (!StringUtils.isBlank(playerId)) {
				// nextPlayer = board.getNextplayer().getNextplayer();
				nextPlayer = playerId;
			}
			this.player = nextPlayer;
			log.info("----------------游戏开始，间隔时间是" + timer);
			// 合并代码，玩家 出牌超时处理和 玩家出牌统一使用一处代码
			BMDataContext.getZhajinhuaEngine().takeCardsRequest(this.gameRoom.getId(), this.player, orgi, true, null);
		}

		// String playerId;
		// if (gameRoom.getParentid() != null) {
		// // 拿到当前房间该环节的操作人员
		// playerId = gameRoom.getParentid();
		// } else {
		// playerId = player;
		// }
		// PlayUserClient playUser = (PlayUserClient)
		// CacheHelper.getGamePlayerCacheBean().getPlayer(playerId, orgi);
		// if (playUser != null) {
		// String playtype = playUser.getPlayertype();
		// // 如果是真人（托管玩家、离开玩家）超时了就调用弃牌，然后在通知前端
		// if (timer == BMDataContext.JINHUA_NORMAL_GAME_TIME
		// && (playtype.equals(BMDataContext.PlayerTypeEnum.NORMAL.toString())
		// || playtype.equals(BMDataContext.PlayerTypeEnum.LEAVE.toString())
		// || playtype.equals(BMDataContext.PlayerTypeEnum.OFFLINE.toString()))) {
		// ZhajinhuaTakeCards zhajinhuaTakeCards = new ZhajinhuaTakeCards();
		// zhajinhuaTakeCards.setUserid(playUser.getId());
		// zhajinhuaTakeCards.setActionType(3);
		// BMDataContext.getZhajinhuaEngine().execGiveup(playUser, gameRoom.getId(),
		// zhajinhuaTakeCards);
		// ActionTaskUtils.sendEvent("zhajinhuatakecards", zhajinhuaTakeCards,
		// gameRoom);
		// log.info("----------------到时弃牌" + zhajinhuaTakeCards.getUserid());
		// } else {
		// // 获取到牌局
		// ZhajinhuaBoard board = (ZhajinhuaBoard)
		// CacheHelper.getBoardCacheBean().getCacheObject(gameRoom.getId(),
		// gameRoom.getOrgi());
		// String nextPlayer = board.getBanker();
		// NextPlayer nextp = board.getNextplayer();
		// playerId = nextp.getNextplayer();
		// // 若下一个出牌的人不为空则覆盖庄家，否则庄家先出牌
		// if (!StringUtils.isBlank(playerId)) {
		// // nextPlayer = board.getNextplayer().getNextplayer();
		// nextPlayer = playerId;
		// }
		// this.player = nextPlayer;
		// log.info("----------------游戏开始，间隔时间是" + timer);
		// // 合并代码，玩家 出牌超时处理和 玩家出牌统一使用一处代码
		// BMDataContext.getZhajinhuaEngine().takeCardsRequest(this.gameRoom.getId(),
		// this.player, orgi, true,
		// null);
		// }
		// }
		//
		// // 后端并且开始执行操作
		// Map<String, String> map = new HashMap<String, String>();
		// log.info("间隔时间为" + sleepTime + ";userId=" + zhajinhuaTakeCards.getUserid() +
		// ";做了什么="
		// + zhajinhuaTakeCards.getActionType());
		// // 操作类型：1、加注2、跟注3、弃牌4、比牌
		// if (zhajinhuaTakeCards.getActionType() == 1 ||
		// zhajinhuaTakeCards.getActionType() == 2) {
		// // GameRoom room = (GameRoom) CacheHelper.getGameRoomCacheBean()
		// // .getCacheObject(zhajinhuaTakeCards.getRoomId(),
		// BMDataContext.SYSTEM_ORGI);
		// map.put("gametype", BMDataContext.GameTypeEnum.JINHUA.toString());
		// map.put("betcoin", zhajinhuaTakeCards.getBetCoin() + "");
		//
		// ActionTaskUtils.sendEvent("zhajinhuatakecards", zhajinhuaTakeCards,
		// gameRoom);
		// // 调用下注方法
		// BMDataContext.getZhajinhuaEngine().execBet(playUserClient, gameRoom, new
		// BetStatus(), map);
		// System.out.println("-------------------------------" + playUserClient.getId()
		// + "下注打断记时");
		// // 激活注册机到下一步
		// BMDataContext.getZhajinhuaEngine().takeCardsRequest(gameRoom.getId(),
		// board.getNextplayer().getNextplayer(), playUserClient.getOrgi(), true, null);
		// } else if (zhajinhuaTakeCards.getActionType() == 3) {
		// ActionTaskUtils.sendEvent("zhajinhuatakecards", zhajinhuaTakeCards,
		// gameRoom);
		// BMDataContext.getZhajinhuaEngine().execGiveup(playUserClient,
		// zhajinhuaTakeCards.getRoomId(), zhajinhuaTakeCards);
		// } else if (zhajinhuaTakeCards.getActionType() == 4) {
		// map.put("anotherPlayer", zhajinhuaTakeCards.getCompareUserid());
		// JSONObject json = new JSONObject();
		// json.put("command", "comparecard");
		// json = BMDataContext.getZhajinhuaEngine().execCompareCard(playUserClient,
		// board, json, map);
		// Map<String, Object> cardInfoMap = (Map<String, Object>) json.get("cards");
		// String winnerUserId = "";
		// // 根据输赢，传入赢家userid
		// if (cardInfoMap.get("flag").toString().equals("1")) {
		// winnerUserId = zhajinhuaTakeCards.getUserid();
		// } else if (cardInfoMap.get("flag").toString().equals("2")) {
		// winnerUserId = zhajinhuaTakeCards.getCompareUserid();
		// }
		// // 设置比牌赢了的玩家id
		// zhajinhuaTakeCards.setCompareWinUserid(winnerUserId);
		// ActionTaskUtils.sendEvent("zhajinhuatakecards", zhajinhuaTakeCards,
		// gameRoom);
		// int currentPlayerNum =
		// Integer.parseInt(json.get("currentPlayerNum").toString());
		// // 存活并且未弃牌人数大于1游戏继续，未弃牌人数小于2前台发起结算
		// if (currentPlayerNum > 1) {
		// log.info("-----------------------" + zhajinhuaTakeCards.getUserid() +
		// "比牌打断记时");
		// // 激活注册机到下一步
		// BMDataContext.getZhajinhuaEngine().takeCardsRequest(zhajinhuaTakeCards.getRoomId(),
		// board.getNextplayer().getNextplayer(), gameRoom.getOrgi(), true, null);
		// } else {
		// log.info("--------------------------------------比牌后人数不够进入结算");
		// // 进入下一步结算 激活注册机到下一步
		// GameUtils.getGame(gameRoom.getPlayway(), gameRoom.getOrgi()).change(gameRoom,
		// BeiMiGameEvent.ALLCARDS.toString()); // 通知状态机
		// }
		// }
	}
}
